#-*-coding:utf-8-*-
import json
import subprocess
# import socket
import sqlite3

import sys
import os

#reload(sys)
#sys.setdefaultencoding('utf-8')
# import time
#
# import datetime
# import threading

G_base_path = os.path.dirname(os.path.dirname(__file__.replace("\\", "/")))
G_com_path = G_base_path + "/base/com_lib"
G_cgtw_path = G_base_path + "/base"
G_plugin_lib_path = G_base_path + '/timeaxis_plugin/lib'
G_cgtw_pyside = G_base_path +'/lib/pyside'
timeaxis_plugin_path = os.path.dirname(__file__.replace("\\", "/"))

if not G_base_path in sys.path:
    sys.path.append(G_base_path)
if not G_com_path in sys.path:
    sys.path.append(G_com_path)
if not G_cgtw_path in sys.path:
    sys.path.append(G_cgtw_path)
if not G_plugin_lib_path in sys.path:
    sys.path.append(G_plugin_lib_path)
if not G_cgtw_pyside in sys.path:
    sys.path.append(G_cgtw_pyside)
# from PySide2 import QtGui,QtCore,QtWidgets
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from com_message_box import *
# from com_work_log import *
# from com_function import *
import cgtw2

class SQLHandler(object):

    def __init__(self,db_path):
        super(SQLHandler, self).__init__()
        self.db_path = db_path
        db_dir = os.path.dirname(self.db_path)
        if not os.path.exists(db_dir):
            os.makedirs(db_dir)
        self.conn = sqlite3.connect(self.db_path)
        self.cursor = self.conn.cursor()
        self.init_table()

    def init_table(self):

        sql = '''
        create table if not exists task(
        id int primary key ,
        cg_id varchar(200) not null,
        database varchar(100) not null,
        project varchar(100) not null,
        asset_shot_name varchar(200) not null,
        dir varchar(200) not null)
        '''
        self.cursor.execute(sql)
        self.conn.commit()

    def save_task(self,task_data):
        sql ="replace into task(cg_id,database,project,asset_shot_name,dir) values " \
             "('{0}','{1}','{2}','{3}','{4}') ".format(task_data['cg_id'],task_data['database'],
                                                                         task_data['entity_name'],task_data['asset_shot'],task_data['dir'])

        self.cursor.execute(sql)
        self.conn.commit()

    def select_task(self,cg_id):
        data = {}
        sql = "select cg_id,database,project,asset_shot_name,dir from task where cg_id ='{}'".format(cg_id)
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        if result:
            data['cg_id'],data['database'],data['project'],data['asset_shot_name'],data['dir'] = result
        # print(result)
        return data

    def get_all_tasks(self):
        data = {}
        sql = "select project,asset_shot_name,dir from task"
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        if result:
            for i in result:
                project,asset_shot_name,dir_path = i
                if project not in data.keys():
                    data[project] = [(asset_shot_name,dir_path)]
                else:
                    data[project].append((asset_shot_name,dir_path))
        return data




    def close(self):
        self.conn.close()


class LocalInfo(QWidget):
    dir_path_Signal = Signal(str)
    def __init__(self,all_tasks):
        super(LocalInfo, self).__init__()
        self.all_tasks = all_tasks
        self.asset_shot_name_dir_map = {}
        self.btn_style="""QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.setStyleSheet(
            'QWidget{background-color:rgb(75,75,75);color:rgb(200,200,200)}')
        self.setWindowTitle(u'查询本地工程')
        self.main_layout = QHBoxLayout()
        self.project_list = QListWidget()
        self.project_list.setMaximumWidth(85)
        self.project_list.clicked.connect(self._show_asset_shot)

        self.asset_shot_layout = QVBoxLayout()
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton(u'查询')
        self.search_btn.setStyleSheet(self.btn_style)
        self.search_btn.clicked.connect(self._filter_shot)
        self.clear_btn = QPushButton(u'清空')
        self.clear_btn.setStyleSheet(self.btn_style)
        self.clear_btn.clicked.connect(self._clear_filter)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.search_layout.addWidget(self.clear_btn)
        self.asset_shot_list = QListWidget()
        self.asset_shot_list.doubleClicked.connect(self._choose_asset_shot)
        self.asset_shot_layout.addLayout(self.search_layout)
        self.asset_shot_layout.addWidget(self.asset_shot_list)

        self.main_layout.addWidget(self.project_list)
        self.main_layout.addLayout(self.asset_shot_layout)
        self.setLayout(self.main_layout)
        
        self.init_tasks(self.all_tasks)

    def init_tasks(self,tasks):
        if tasks:
            self.project_list.addItems(list(tasks.keys()))

    def _show_asset_shot(self,index):
        self.asset_shot_list.clear()
        self.asset_shot_name_dir_map = {}
        item = self.project_list.itemFromIndex(index)
        text = item.text()
        tasks = self.all_tasks.get(text,[])
        if tasks:
            for i in tasks:
                asset_shot_name,dir_path = i
                item = QListWidgetItem()
                item.setText(asset_shot_name)
                self.asset_shot_name_dir_map[asset_shot_name] = dir_path
                self.asset_shot_list.addItem(item)
            self.asset_shot_list.sortItems()

    def _choose_asset_shot(self,index):
        item = self.asset_shot_list.itemFromIndex(index)
        text = item.text()
        dir_path = self.asset_shot_name_dir_map.get(text,'')
        # print('dir_path:',dir_path)
        self.dir_path_Signal.emit(dir_path)

    def filter_item(self, text):
        try:
            for i in range(self.asset_shot_list.count()):
                item = self.asset_shot_list.item(i)
                show_text = item.text()
                if text not in show_text:
                    item.setHidden(True)
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))


    def show_all(self):
        for i in range(self.asset_shot_list.count()):
            item = self.asset_shot_list.item(i)
            item.setHidden(False)


    def _clear_filter(self):
        self.search_edit.clear()
        self.show_all()

    def _filter_shot(self):
        """
        filter shot
        :return:
        """
        text = self.search_edit.text()
        if text:
            self.filter_item(text)
        else:
            self.show_all()

    def _text_edited(self, ha):
        if not ha:
            self.show_all()

class LaunchMaya(QWidget):
    def __init__(self):
        super(LaunchMaya,self).__init__()
        #全局变量
        self.t_tw = cgtw2.tw()
        self.t_module = self.t_tw.client.get_module()
        self.t_id_list = self.t_tw.client.get_id()
        self.t_database = self.t_tw.client.get_database()
        self.db_path = r'C:\timeaxis_my_task\db\local_task_info.db'
        self.db_handler = SQLHandler(self.db_path)

        self._dir = ''
        self.eps_path =''  #当前工程集数路径
        self.asset_shot_path = ''  #该项目资产/镜头路径
        self.data = {}
        
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.software_font = QFont('',12,65)

        self.setWindowTitle('选中的任务信息')
        self.setStyleSheet(
            'QWidget{background-color:rgb(75,75,75);color:rgb(200,200,200)}')
        # self.setMinimumWidth(900)
        self.main_layout=QVBoxLayout()
        self.init_layout = QHBoxLayout()
        self.driver_btn = QPushButton('E:/')
        self.driver_btn.setStyleSheet(self.btn_style)
        self.driver_btn.clicked.connect(self._drive_changed)
        self.sequence_radio = QRadioButton('转序列图')
        self.create_btn = QPushButton(u'初始工程')
        self.create_btn.setStyleSheet(self.btn_style)
        self.create_btn.clicked.connect(self._init_project)
        self.init_layout.addWidget(self.driver_btn)
        self.init_layout.addWidget(self.sequence_radio)
        self.init_layout.addWidget(self.create_btn)
        self.search_layout = QHBoxLayout()
        self.search_btn = QPushButton(u'查询工程')
        self.search_btn.setStyleSheet(self.btn_style)
        self.search_btn.clicked.connect(self._open_local_window)
        self.search_layout.addWidget(self.search_btn)
        self.create_layout = QHBoxLayout()
        self.create_btn = QPushButton(u'新建maya工程')
        self.create_btn.setStyleSheet(self.btn_style)
        self.create_btn.clicked.connect(self._open_maya)
        self.create_layout.addWidget(self.create_btn)

        self.check_project()
        
        # self.project_file_layout = QHBoxLayout()
        # self.pftrack_layout = QVBoxLayout()
        # self.pftrack_label = QLabel('PFtrack')
        # self.pftrack_list = QListWidget()
        # self.pftrack_list.setMaximumWidth(150)
        # # self.pftrack_list.setMaximumHeight(70)
        # self.pftrack_layout.addWidget(self.pftrack_label)
        # self.pftrack_layout.addWidget(self.pftrack_list)
        # self.ma_layout = QVBoxLayout()
        # self.ma_label = QLabel('Maya')
        # self.ma_list = QListWidget()
        # self.ma_list.setMaximumWidth(150)
        # # self.ma_list.setMaximumHeight(70)
        # self.ma_list.doubleClicked.connect(self._choose_ma)
        # self.ma_layout.addWidget(self.ma_label)
        # self.ma_layout.addWidget(self.ma_list)

        # self.project_file_layout.addLayout(self.pftrack_layout)
        # self.project_file_layout.addLayout(self.ma_layout)
        
        self.main_layout.setSpacing(10)
        self.main_layout.addLayout(self.init_layout)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addLayout(self.create_layout)
        self.init_pipeline_widget()
        # self.main_layout.addLayout(self.project_file_layout)

        self.setLayout(self.main_layout)

        


    def check_project(self):
        """  
        check local db for this asset/shot information
        """
        self.data = self.get_task()
        cg_id = self.data.get('cg_id','')
        #self.ma_list.clear()
        task_data = self.db_handler.select_task(cg_id)
        self._dir = task_data.get('dir','')
        print('dir:',task_data.get('dir',''))
        # pipeline = self.data['pipeline']
        # if task_data:
        #     if pipeline.startswith('mm'):
        #         self._update_mm_frame(task_data['dir'])


    def update_list(self,local_dir_path):
        #self.ma_list.clear()
        self._dir = local_dir_path  #task_data['dir']
        dirve = os.path.splitdrive(self._dir)[0]+'/'
        self.driver_btn.setText(dirve)
        ma_dir = os.path.join(self._dir,'ma')
        if os.path.exists(ma_dir):
            ma_names = os.listdir(ma_dir)
            for i in ma_names:
                item = QListWidgetItem()
                item.setText(i)
                self.ma_list.addItem(item)

    def init_pipeline_widget(self):
        """
        mm:
            SynthEyes    *.sni     
            3DEqualizer        *.3de
            PFTrack    *.pfmp    (项目管理链接文件，非独立文件)  
            Maya   *.ma
            Nuke  *.nk

        mod:
            Maya  *.ma
            Zbursh     *.ZTL(工具文件)
            Mari    *.mri (项目链接文件)
            Substance painter   *.
            SpeedTree   *.spm
            AE   *.aep
            Nuke  *.nk
        ani:
            Maya   *.ma
            After Effect   *.aep
            Premiere   *.prproj  (项目文件)

        """
        pipeline = self.data['pipeline']
        if pipeline.startswith('mm'):
            self.mm_frame = QFrame()
            self.mm_layout = QVBoxLayout()

            self.mm_sub_layout1 = QHBoxLayout()
            self.mm_SynthEyes_layout = QVBoxLayout()
            self.mm_SynthEyes_label = QLabel(u'SynthEyes')
            self.mm_SynthEyes_label.setFont(self.software_font)
            self.mm_SynthEyes_label.setAlignment(Qt.AlignCenter)
            mm_SynthEyes_path = os.path.join(self._dir,'systheyes')
            self.mm_SynthEyes_list = QListWidget()
            self.mm_SynthEyes_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.mm_SynthEyes_list,mm_SynthEyes_path))
            self.mm_SynthEyes_layout.addWidget(self.mm_SynthEyes_label)
            self.mm_SynthEyes_layout.addWidget(self.mm_SynthEyes_list)
            self.mm_3de_layout = QVBoxLayout()
            self.mm_3de_label = QLabel(u'3DEqualizer')
            self.mm_3de_label.setFont(self.software_font)
            self.mm_3de_label.setAlignment(Qt.AlignCenter)
            self.mm_3de_list = QListWidget()
            self.mm_3de_layout.addWidget(self.mm_3de_label)
            self.mm_3de_layout.addWidget(self.mm_3de_list)
            self.mm_pf_layout = QVBoxLayout()
            self.mm_pf_label = QLabel(u'PFTrack')
            self.mm_pf_label.setFont(self.software_font)
            self.mm_pf_label.setAlignment(Qt.AlignCenter)
            self.mm_pf_list = QListWidget()
            self.mm_pf_layout.addWidget(self.mm_pf_label)
            self.mm_pf_layout.addWidget(self.mm_pf_list)
            self.mm_sub_layout1.addLayout(self.mm_SynthEyes_layout)
            self.mm_sub_layout1.addLayout(self.mm_3de_layout)
            self.mm_sub_layout1.addLayout(self.mm_pf_layout)

            self.mm_sub_layout2 = QHBoxLayout()
            self.mm_maya_layout = QVBoxLayout()
            self.mm_maya_label = QLabel(u'Maya')
            self.mm_maya_label.setFont(self.software_font)
            self.mm_maya_label.setAlignment(Qt.AlignCenter)
            mm_maya_path = os.path.join(self._dir,'ma','scene')
            self.mm_maya_list = QListWidget()
            self.mm_maya_list.doubleClicked.connect(lambda m :self._start_choose_file(m,self.mm_maya_list,mm_maya_path))
            self.mm_maya_layout.addWidget(self.mm_maya_label)
            self.mm_maya_layout.addWidget(self.mm_maya_list)
            self.mm_nuke_layout = QVBoxLayout()
            self.mm_nuke_label = QLabel(u'Nuke')
            self.mm_nuke_label.setFont(self.software_font)
            self.mm_nuke_label.setAlignment(Qt.AlignCenter)
            mm_nuke_path = os.path.join(self._dir,'nuke')
            self.mm_nuke_list = QListWidget()
            self.mm_nuke_list.doubleClicked.connect(lambda m :self._start_choose_file(m,self.mm_nuke_list,mm_nuke_path))
            self.mm_nuke_layout.addWidget(self.mm_nuke_label)
            self.mm_nuke_layout.addWidget(self.mm_nuke_list)
            self.mm_sub_layout2.addLayout(self.mm_maya_layout)
            self.mm_sub_layout2.addLayout(self.mm_nuke_layout)
      
            self.mm_layout.addLayout(self.mm_sub_layout1)
            self.mm_layout.addLayout(self.mm_sub_layout2)
            self.mm_frame.setLayout(self.mm_layout)
            self.main_layout.addWidget(self.mm_frame)

            self._update_mm_frame(self._dir)


        if pipeline.startswith('mod'):
            self.mod_frame = QFrame()
            self.mod_layout = QVBoxLayout()

            self.mod_sub_layout1 = QHBoxLayout()
            self.mod_maya_layout = QVBoxLayout()
            self.mod_maya_label = QLabel('Maya')
            self.mod_maya_label.setFont(self.software_font)
            self.mod_maya_label.setAlignment(Qt.AlignCenter)
            mod_maya_path = os.path.join(self._dir,'ma')
            self.mod_maya_list = QListWidget()
            self.mod_maya_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.mod_maya_list,mod_maya_path))
            self.mod_maya_layout.addWidget(self.mod_maya_label)
            self.mod_maya_layout.addWidget(self.mod_maya_list)
            self.mod_zb_layout = QVBoxLayout()
            self.mod_zb_label = QLabel(u'Zbursh')
            self.mod_zb_label.setFont(self.software_font)
            self.mod_zb_label.setAlignment(Qt.AlignCenter)
            self.mod_zb_list = QListWidget()
            self.mod_zb_layout.addWidget(self.mod_zb_label)
            self.mod_zb_layout.addWidget(self.mod_zb_list)
            self.mod_Mari_layout = QVBoxLayout()
            self.mod_Mari_label = QLabel(u'Mari')
            self.mod_Mari_label.setFont(self.software_font)
            self.mod_Mari_label.setAlignment(Qt.AlignCenter)
            self.mod_Mari_list = QListWidget()
            self.mod_Mari_layout.addWidget(self.mod_Mari_label)
            self.mod_Mari_layout.addWidget(self.mod_Mari_list)
            self.mod_sub_layout1.addLayout(self.mod_maya_layout)
            self.mod_sub_layout1.addLayout(self.mod_zb_layout)
            self.mod_sub_layout1.addLayout(self.mod_Mari_layout)

            self.mod_sub_layout2 = QHBoxLayout()
            self.mod_sp_layout = QVBoxLayout()
            self.mod_sp_label = QLabel(u'Substance Painter')
            self.mod_sp_label.setFont(self.software_font)
            self.mod_sp_label.setAlignment(Qt.AlignCenter)
            self.mod_sp_list = QListWidget()
            self.mod_sp_layout.addWidget(self.mod_sp_label)
            self.mod_sp_layout.addWidget(self.mod_sp_list)
            self.mod_SpeedTree_layout = QVBoxLayout()
            self.mod_SpeedTree_label = QLabel(u'SpeedTree')
            self.mod_SpeedTree_label.setFont(self.software_font)
            self.mod_SpeedTree_label.setAlignment(Qt.AlignCenter)
            self.mod_SpeedTree_list = QListWidget()
            self.mod_SpeedTree_layout.addWidget(self.mod_SpeedTree_label)
            self.mod_SpeedTree_layout.addWidget(self.mod_SpeedTree_list)
            self.mod_ps_layout = QVBoxLayout()
            self.mod_ps_label = QLabel(u'PhotoShop')
            self.mod_ps_label.setFont(self.software_font)
            self.mod_ps_label.setAlignment(Qt.AlignCenter)
            self.mod_ps_list = QListWidget()
            self.mod_ps_layout.addWidget(self.mod_ps_label)
            self.mod_ps_layout.addWidget(self.mod_ps_list)
            self.mod_sub_layout2.addLayout(self.mod_sp_layout)
            self.mod_sub_layout2.addLayout(self.mod_SpeedTree_layout)
            self.mod_sub_layout2.addLayout(self.mod_ps_layout)

            self.mod_sub_layout3 = QHBoxLayout()
            self.mod_AE_layout = QVBoxLayout()
            self.mod_AE_label = QLabel(u'AE')
            self.mod_AE_label.setFont(self.software_font)
            self.mod_AE_label.setAlignment(Qt.AlignCenter)
            self.mod_AE_list = QListWidget()
            self.mod_AE_layout.addWidget(self.mod_AE_label)
            self.mod_AE_layout.addWidget(self.mod_AE_list)
            self.mod_nuke_layout = QVBoxLayout()
            self.mod_nuke_label = QLabel(u'Nuke' )
            self.mod_nuke_label.setFont(self.software_font)
            self.mod_nuke_label.setAlignment(Qt.AlignCenter)
            self.mod_nuke_list = QListWidget()
            self.mod_nuke_layout.addWidget(self.mod_nuke_label)
            self.mod_nuke_layout.addWidget(self.mod_nuke_list)
            self.mod_sub_layout3.addLayout(self.mod_AE_layout)
            self.mod_sub_layout3.addLayout(self.mod_nuke_layout)
      
            self.mod_layout.addLayout(self.mod_sub_layout1)
            self.mod_layout.addLayout(self.mod_sub_layout2)
            self.mod_layout.addLayout(self.mod_sub_layout3)
            self.mod_frame.setLayout(self.mod_layout)
            self.main_layout.addWidget(self.mod_frame)


        if pipeline.startswith('rig'):
            self.rig_frame = QFrame()
            self.rig_layout = QVBoxLayout()

            self.rig_sub_layout1 = QHBoxLayout()
            self.rig_maya_layout = QVBoxLayout()
            self.rig_maya_label = QLabel(u'Maya')
            self.rig_maya_label.setFont(self.software_font)
            self.rig_maya_label.setAlignment(Qt.AlignCenter)
            rig_maya_path = os.path.join(self._dir,'ma')
            self.rig_maya_list = QListWidget()
            self.rig_maya_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.mod_maya_label_list,rig_maya_path))
            self.rig_maya_layout.addWidget(self.rig_maya_label)
            self.rig_maya_layout.addWidget(self.rig_maya_list)
            self.rig_wrap3_layout = QVBoxLayout()
            self.rig_wrap3_label = QLabel(u'Wrap3')
            self.rig_wrap3_label.setFont(self.software_font)
            self.rig_wrap3_label.setAlignment(Qt.AlignCenter)
            rig_wrap3_path = os.path.join(self._dir,'wrap3')
            self.rig_wrap3_list = QListWidget()
            self.rig_wrap3_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.rig_wrap3_list,rig_wrap3_path))
            self.rig_wrap3_layout.addWidget(self.rig_wrap3_label)
            self.rig_wrap3_layout.addWidget(self.rig_wrap3_list)
            self.rig_zb_layout = QVBoxLayout()
            self.rig_zb_label = QLabel(u'Zbrush')
            self.rig_zb_label.setFont(self.software_font)
            self.rig_zb_label.setAlignment(Qt.AlignCenter)
            rig_zb_path = os.path.join(self._dir,'zbrush')
            self.rig_zb_list = QListWidget()
            self.rig_zb_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.rig_wrap3_list,rig_zb_path))
            self.rig_zb_layout.addWidget(self.rig_zb_label)
            self.rig_zb_layout.addWidget(self.rig_zb_list)
            self.rig_sub_layout1.addLayout(self.rig_maya_layout)
            self.rig_sub_layout1.addLayout(self.rig_wrap3_layout)
            self.rig_sub_layout1.addLayout(self.rig_zb_layout)

            self.rig_layout.addLayout(self.rig_sub_layout1)
            self.rig_frame.setLayout(self.rig_layout)
            self.main_layout.addWidget(self.rig_frame)


        if pipeline.startswith('ani'):
            self.ani_frame = QFrame()
            self.ani_layout = QVBoxLayout()

            self.ani_sub_layout1 = QHBoxLayout()
            self.ani_maya_layout = QVBoxLayout()
            self.ani_maya_label = QLabel(u'Maya')
            self.ani_maya_label.setFont(self.software_font)
            self.ani_maya_label.setAlignment(Qt.AlignCenter)
            ani_maya_path = os.path.join(self._dir,'zbrush')
            self.ani_maya_list = QListWidget()
            self.ani_maya_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.ani_maya_list,ani_maya_path))
            self.ani_maya_layout.addWidget(self.ani_maya_label)
            self.ani_maya_layout.addWidget(self.ani_maya_list)
            self.ani_nuke_layout = QVBoxLayout()
            self.ani_nuke_label = QLabel(u'Nuke')
            self.ani_nuke_label.setFont(self.software_font)
            self.ani_nuke_label.setAlignment(Qt.AlignCenter)
            ani_nuke_path = os.path.join(self._dir,'nuke')
            self.ani_nuke_list = QListWidget()
            self.ani_nuke_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.ani_nuke_list,ani_nuke_path))
            self.ani_nuke_layout.addWidget(self.ani_nuke_label)
            self.ani_nuke_layout.addWidget(self.ani_nuke_list)
            self.ani_sub_layout1.addLayout(self.ani_maya_layout)
            self.ani_sub_layout1.addLayout(self.ani_nuke_layout)
            
            self.ani_sub_layout2 = QHBoxLayout()
            self.ani_ae_layout = QVBoxLayout()
            self.ani_ae_label = QLabel(u'AE' )
            self.ani_ae_label.setFont(self.software_font)
            self.ani_ae_label.setAlignment(Qt.AlignCenter)
            ani_ae_path = os.path.join(self._dir,'ae')
            self.ani_ae_list = QListWidget()
            self.ani_ae_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.ani_maya_list,ani_ae_path))
            self.ani_ae_layout.addWidget(self.ani_ae_label)
            self.ani_ae_layout.addWidget(self.ani_ae_list)
            self.ani_pr_layout = QVBoxLayout()
            self.ani_pr_label = QLabel(u'PR')
            self.ani_pr_label.setFont(self.software_font)
            self.ani_pr_label.setAlignment(Qt.AlignCenter)
            ani_pr_path = os.path.join(self._dir,'pr')
            self.ani_pr_list = QListWidget()
            self.ani_pr_list.doubleClicked.connect(lambda s :self._start_choose_file(s,self.ani_pr_list,ani_ae_path))
            self.ani_pr_layout.addWidget(self.ani_pr_label)
            self.ani_pr_layout.addWidget(self.ani_pr_list)
            self.ani_sub_layout2.addLayout(self.ani_ae_layout)
            self.ani_sub_layout2.addLayout(self.ani_pr_layout)






            self.ani_layout.addLayout(self.ani_sub_layout1)
            self.ani_frame.setLayout(self.ani_layout)
            self.main_layout.addWidget(self.ani_frame)

    def _update_mm_frame(self,local_path):
        """
        刷新跟踪本地工程列表
        集数目录下：
            PFTrack -> pf
        镜头目录下：
            SynthEyes -> systheyes
            3DEqualizer -> 3de
            Maya -> ma/scene
            Nuke -> nuke
        """
        if os.path.exists(local_path):
            self.asset_shot_path = os.path.dirname(local_path)
            self.eps_path = os.path.dirname(self.asset_shot_path)
            pf_path = os.path.join(self.eps_path,'pf')
            #update self.mm_pf_list
            pf_listdir = os.listdir(pf_path)
            pf_files = []
            for p in pf_listdir:
                if p.endswith('pfmp'):
                    pf_files.append(p)
            self.mm_pf_list.clear()
            if pf_files:
                self.mm_pf_list.addItems(pf_files)
                self.mm_pf_list.sortItems()
        
            #update self.mm_3de_list
            mm_3de_path = os.path.join(local_path,'3de')
            mm_3de_listdir = os.listdir(mm_3de_path)
            mm_3de_files = []
            for d in mm_3de_listdir:
                if d.endswith('3de'):
                    mm_3de_files.append(d)
            self.mm_3de_list.clear()
            if mm_3de_files:
                self.mm_3de_list.addItems(mm_3de_files)


            #update self.mm_SynthEyes_list
            mm_SynthEyes_path = os.path.join(local_path,'systheyes')
            mm_SynthEyes_listdir = os.listdir(mm_SynthEyes_path)
            mm_SynthEyes_files = []
            for s in mm_SynthEyes_listdir:
                if s.endswith('sni'):
                    mm_SynthEyes_files.append(s)
            self.mm_SynthEyes_list.clear()
            if mm_SynthEyes_files:
                self.mm_SynthEyes_list.addItems(mm_SynthEyes_files)

            #update self.mm_maya_list
            mm_maya_path = os.path.join(local_path,'ma','scene')
            mm_maya_listdir = os.listdir(mm_maya_path)
            mm_maya_files = []
            for m in mm_maya_listdir:
                if m.endswith('ma'):
                    mm_maya_files.append(m)
            self.mm_maya_list.clear()
            if mm_maya_files:
                self.mm_maya_list.addItems(mm_maya_files)

            #update self.mm_nuke_list
            mm_nuke_path = os.path.join(local_path,'nuke')
            mm_nuke_listdir = os.listdir(mm_nuke_path)
            mm_nuk_files = []
            for n in mm_nuke_listdir:
                if n.endswith('nk'):
                    mm_nuk_files.append(n)
            self.mm_nuke_list.clear()
            if mm_nuk_files:
                self.mm_nuke_list.addItems(mm_nuk_files)


    def _init_project(self):
        if self.data:
            # drive_path = self.driver_btn.text()
            # project = self.data['entity_name']
            # eps = self.data['eps']
            # shot = self.data['asset_shot']
            pipeline = self.data['pipeline']
            # dir_path = os.path.join(drive_path, project, eps, shot, pipeline)
            
            dir_path = ''
            if pipeline.startswith('mm'):
                dir_path = self.create_mm_dir()
            elif pipeline.startswith('mod'):
                dir_path = self.create_mod_dir()
            elif pipeline.startswith('rig'):
                dir_path = self.create_rig_dir()
            elif pipeline.startswith('ani'):
                dir_path = self.create_ani_dir()
            elif pipeline.startswith('env'):
                dir_path = self.create_env_dir()
            elif pipeline.startswith('lgt'):
                dir_path = self.create_lgt_dir()                
            # self.create_shot(dir_path)
            self.data['dir'] = dir_path
            self.db_handler.save_task(self.data)
            os.startfile(dir_path)

    def _start_choose_file(self,index,list_widget,pre_path):
        """
        open choose file
        """
        item = list_widget.itemFromIndex(index)
        text = item.text()
        file_path = os.path.join(pre_path,text)
        print('_start_choose_file:',file_path)
        # try:
        #     os.startfile(file_path)
        # except Exception as _start_choose_file_ERR:
        #     print(str(_start_choose_file_ERR))


    def create_mm_dir(self):
        drive_path = self.driver_btn.text()
        project = self.data['entity_name']
        eps = self.data['eps']
        asset_shot = self.data['asset_shot']
 
        
        mm_asset_path = os.path.join(drive_path, project,'mm_asset')
        if not os.path.exists(mm_asset_path):
            os.makedirs(mm_asset_path)
        
        pf_path = os.path.join(drive_path,project,eps,'pf')
        if not os.path.exists(pf_path):
            os.makedirs(pf_path)       
        
        mm_path = os.path.join(drive_path, project, eps, asset_shot, self.data['pipeline'])
        if not os.path.exists(mm_path):
            os.makedirs(mm_path) 
        mm_dirs = ['3de','abc','fbx','ma','nuke','stmap','systheyes','ud','video']
        for i in mm_dirs:
            dirs_path = os.path.join(mm_path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)       
        return mm_path

    def create_mod_dir(self):
        dirve_path = self.driver_btn.text()
        project = self.data['entity_name']
        asset_shot = self.data['asset_shot']
  
        mod_path = os.path.join(dirve_path, project, asset_shot, self.data['pipeline'])
        if not os.path.exists(mod_path):
            os.makedirs(mod_path) 
        mod_dirs = ['ae','fbx','ma','mari','nuke','other','ps','sp','speedtree','video','zbrush']
        for i in mod_dirs:
            dirs_path = os.path.join(mod_path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)    
        return mod_path

    def create_rig_dir(self):
        dirve_path = self.driver_btn.text()
        project = self.data['entity_name']
        asset_shot = self.data['asset_shot']

        rig_asset_path = os.path.join(dirve_path, project,'rig_asset')
        if not os.path.exists(rig_asset_path):
            os.makedirs(rig_asset_path) 
        rig_path = os.path.join(drive_path, project, asset_shot, self.data['pipeline'])
        if not os.path.exists(rig_path):
            os.makedirs(rig_path) 
        rig_dirs = ['abc','cfx','fbx','ma','mod','mudbox','other','obj','wrap3','video','zbrush']
        for i in rig_dirs:
            dirs_path = os.path.join(rig_dirs, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)   
        return rig_path

    def create_ani_dir(self):
        dirve_path = self.driver_btn.text()
        project = self.data['entity_name']
        asset_shot = self.data['asset_shot']       
        module = self.data['module']
        ani_path = ''
        ani_dirs = []
        if module =='asset':
            ani_path = os.path.join(drive_path, project, asset_shot, self.data['pipeline'])
            if not os.path.exists(ani_path):
                os.makedirs(ani_path) 
            ani_dirs = ['abc','fbx','ma','video']

        else:
            ani_path = os.path.join(drive_path, project, eps, asset_shot, self.data['pipeline'])
            if not os.path.exists(ani_path):
                os.makedirs(ani_path) 
            ani_dirs = ['abc','ae','cam','fbx','ma','nuke','pr','video']

        for i in ani_dirs:
            dirs_path = os.path.join(ani_path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)  

        return ani_path

    def create_env_dir(self):
        dirve_path = self.driver_btn.text()
        project = self.data['entity_name']
        asset_shot = self.data['asset_shot']
  
        env_path = os.path.join(drive_path, project, asset_shot, self.data['pipeline'])
        if not os.path.exists(env_path):
            os.makedirs(env_path) 
        env_dirs = ['abc','max','fbx','ma','nuke','video','UE','clarrise']
        for i in env_dirs:
            dirs_path = os.path.join(env_path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)    
        return env_path

    def create_lgt_dir(self):
        dirve_path = self.driver_btn.text()
        project = self.data['entity_name']
        asset_shot = self.data['asset_shot']       
       

        lgt_asset_path = os.path.join(drive_path, project,'lgt_asset')
        if not os.path.exists(lgt_asset_path):
            os.makedirs(lgt_asset_path) 
        lgt_path = os.path.join(drive_path, project, eps,asset_shot, self.data['pipeline'])
        if not os.path.exists(lgt_path):
            os.makedirs(lgt_path) 
        lgt_dirs = ['abc','houdini','ma','nuke','video','shot']
        for i in lgt_dirs:
            dirs_path = os.path.join(lgt_path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)   
        return lgt_path


    def create_shot(self, data):
        """
        create project
        :param asset_shot: "asset" or "shot"
        :param pipeline:  pipeline 
        :param path: dir path
        :param shot_info: current shot infomation
        :return:
        """
        if not os.path.exists(path):
            os.makedirs(path)
        dir_list = ['ma', 'geo', 'cam', 'abc', 'tex', 'fbx', 'img', 'nk', 'hda', 'DCC', 'deadline','render','video']
        for i in dir_list:
            dirs_path = os.path.join(path, i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)




    def _drive_changed(self):
        dir = QFileDialog.getExistingDirectory(self, '选择目录')
        # print(dir)
        self.driver_btn.setText(dir)


    def _choose_ma(self,i):
        item = self.ma_list.itemFromIndex(i)
        text = item.text()
        ma_path = os.path.join(self._dir,'ma',text)
        self.openMaya(ma_path=ma_path)


    def _open_local_window(self):
        all_tasks = self.db_handler.get_all_tasks()
        self.local_window = LocalInfo(all_tasks)
        self.local_window.dir_path_Signal.connect(self.update_list)
        self.local_window.show()

    def _open_maya(self):
        driver = self.driver_btn.text()
        self.data['driver'] = driver
        self.setMaya(self.data)

    def getProjectInfo(self):
        t_id_list = self.t_tw.info.get_id('public', 'project',
                                  [["project.database", "=", self.t_database]])
        info = self.t_tw.info.get('public', 'project', t_id_list,['project.code','project.full_name','project.frame_rate','project.path','project.resolution'])
        # os.system('pause')
        project_info = info[0] if info else {}

        data = {}
        data['entity_name'] = project_info.get('project.code','')
        data['full_name'] = project_info.get('project.full_name','')
        data['fps'] = int(project_info.get('project.frame_rate','24'))
        data['resolution'] = project_info.get('project.resolution','2048x1152')
        data['path'] = project_info.get('project.path','')
        return data


    def openMaya(self,data=None,ma_path=None):
        if ma_path:
            os.startfile(ma_path)
        else:
            self.setMaya(data)


    def get_task(self):

        if not self.t_id_list:
            return

        data = self.getProjectInfo()
        text=''
        # for i in self.t_id_list:
        i = self.t_id_list[-1]
        shot_name=' '
        link_id=''
        frame = 0
        description = ''
        eps = ''
        vfx_note = ''
        if self.t_module=='shot':
            shot_name = self.t_tw.task.get(self.t_database, self.t_module, [i], ['shot.shot'])[0][
                'shot.shot']
            link_id = self.t_tw.info.get_id(self.t_database, self.t_module,
                                            [["shot.shot", "=", shot_name]])[0]
            frame = self.t_tw.task.get(self.t_database, self.t_module, [i], ['shot.frame'])[0][
                'shot.frame']
            eps = self.t_tw.task.get(self.t_database, self.t_module, [i], ['shot.eps_name'])[0][
                'shot.eps_name']                   
            description = self.t_tw.task.get(self.t_database, self.t_module, [i], ['shot.description'])[0][
                'shot.description']
            vfx_note = self.t_tw.task.get(self.t_database, self.t_module, [i], ['shot.vfx_note'])[0][
                'shot.vfx_note']
        elif self.t_module=='asset':
            shot_name = self.t_tw.task.get(self.t_database, self.t_module, [i], ['asset.asset_name'])[0][
                'asset.asset_name']
            link_id = self.t_tw.info.get_id(self.t_database, self.t_module,
                                            [["asset.asset_name", "=", shot_name]])[0]
        task_id=self.t_tw.task.get(self.t_database, self.t_module, [i], ['task.id'])[0][
            'task.id']
        cg_id=self.t_database+','+self.t_module+','+task_id
        pipeline = self.t_tw.task.get(self.t_database, self.t_module, [i], ['task.pipeline'])[0][
            'task.pipeline']

        description = vfx_note if vfx_note else description
        data['module'] = self.t_module
        data['pipeline'] = pipeline
        data['asset_shot'] = shot_name
        data['frame'] = int(frame) if frame else 0
        data['description'] = description
        data['cg_id'] = cg_id
        data['eps'] = eps
        data['database'] = self.t_database

        text+=u'项目信息:{}\n\n镜头号:{}  帧数:{} 任务id:{} link_id:{} cg_id:{}\n\n 制作内容描述:{}'.format(data,shot_name,frame,
        task_id,link_id,cg_id,description)

        
        return data
        
        # self.text_brow.setText(text)

    def setMaya(self,data):
        config_path = os.path.join(os.path.dirname(__file__),'config')
        presets_path = os.path.join(config_path,'presets.json')
        if not os.path.exists(config_path):
            os.makedirs(config_path)

        with open(presets_path,'w') as w:
            w.write(json.dumps(data))

        mayaexe_path = r'C:\Program Files\Autodesk\Maya2018\bin\maya.exe'
        exec_script = os.path.join(timeaxis_plugin_path,'preset_maya.py').replace('\\','/')
        subprocess.Popen([mayaexe_path, '-hideConsole','-command', '''python("execfile('{}')")'''.format(exec_script)]) 


if __name__ == '__main__':
    app=QApplication(sys.argv)
    g=LaunchMaya()
    # g.check_project()
    g.show()
    sys.exit(app.exec_())